import { createPool } from 'mysql2/promise';
import dotenv from 'dotenv';
import logger from './logger.js';
import mysql from 'mysql2/promise';

dotenv.config();

// 创建数据库连接池
const pool = mysql.createPool({
  host: process.env.DB_HOST,
  port: process.env.DB_PORT,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME,
  waitForConnections: true,
  connectionLimit: 20, // 连接池中的最大连接数
  queueLimit: 0 // 排队请求的最大数量，0表示无限制
});
console.log('数据库连接配置:', {
  host: process.env.DB_HOST,
  port: process.env.DB_PORT,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME
});
// 测试数据库连接
(async () => {
  try {
    const connection = await pool.getConnection();
    logger.info('成功连接到数据库');
    connection.release();
  } catch (err) {
    logger.error('数据库连接错误:', err.stack);
  }
})();

// 带错误处理和日志记录的查询函数
const query = async (text, params) => {
  const start = Date.now();
  try {
    const [rows] = await pool.execute(text, params);
    const duration = Date.now() - start;
    logger.info(`执行查询: ${text} (${duration}毫秒)`);
    return { rows };
  } catch (err) {
    logger.error(`查询错误: ${text}`, err.stack);
    throw err;
  }
};

export { pool, query };